import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter,Route } from 'react-router-dom';
import { Icon, Popover, ActivityIndicator, Bubble,Result,Tools,Modal,SwipeAction  } from 'weaver-mobile';
import { ListViewPage,TabPage,RouteLayout } from 'weaver-mobile-page';
import equals from 'deep-equal';
import WorkplanListStore from '../../stores/list/WorkplanListStore';

const Item = Popover.Item;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
const getLabel = Tools.getLabel;
const alert = Modal.alert;
const separator = (sectionID, rowID) => (          
  <div
    key={`${sectionID}-${rowID}`}
    style={{
      backgroundColor: '#f3f7fe',
      height: 10,
      borderTop: '0px solid #ECECED',
      borderBottom: '0px solid #ECECED',
    }}
  />
);
// @inject('workplanListStore')
@withRouter
@observer
export default class WorkplanList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      store : new WorkplanListStore(),
      overlay: [
        (<Item key="4" value="scan" data-seed="logId">Scan</Item>),
        (<Item key="5" value="special" style={{ whiteSpace: 'nowrap' }}>My Qrcode</Item>),
        (<Item key="6" value="button ct">
          <span style={{ marginRight: 5 }}>Help</span>
        </Item>),
      ],
      span: [7, 1],
      curWorkplanId:"",
      customHeight:undefined
    };
  }

  componentWillMount(){
    const {match,params} = this.props;
    let ps = params ? params : match.params;
    this.state.store.doNew(this,ps);
  }

  componentDidMount() {
    this.state.store.doInit();
    this.props.onRef && this.props.onRef(this);
  }

  componentWillUnmount() {
    this.state.store.doClear();
  }

  componentWillReceiveProps(nextProps) {
    const pn = this.props.location.pathname;
    //新建日程页面回退,刷新当前页面
    if(pn.indexOf("wpCreateLayout") != -1 || pn.indexOf("wpViewLayout") != -1){
        if(this.props.saveCallBack){
          this.props.saveCallBack();
        }
        this.state.store.doSearch();
        return;
    }
    let tp = {...this.props.params};
    let np = {...nextProps.params};
    if(tp._ec_ismobile){
      eval("delete tp._ec_ismobile");
    }
    if(tp.ismobile){
      eval("delete tp.ismobile");
    }
    if(np._ec_ismobile){
      eval("delete np._ec_ismobile");
    }
    if(np.ismobile){
      eval("delete np.ismobile");
    }
    for(let k in tp){
      if(tp[k] === ""){
        eval("delete tp."+k);
      }
    }
    for(let k in np){
      if(np[k] === ""){
        eval("delete np."+k);
      }
    }
    // console.log("tp",tp);
    // console.log("np",np);
    if (!equals(tp,np)) {
      np.ismobile = 1;
      np._ec_ismobile = true;
      this.state.store.params = np;
      this.state.store.doSearch();
    }
  }

  render() {
    const store = this.state.store;
    const {initResponsed,initSuccessed,initFailedMsg} = store;
    if(initResponsed){
        if(initSuccessed){
          const { list, showCheck, canEdit,wpCreateLayout,wpViewLayout,params } = store;
          const { span, overlay, visible, curWorkplanId, customHeight } = this.state;

          const btns = [];
          btns.push(<i className={'crm-nav-header-icon icon-crm icon-crm-add'} style={{color:"#999"}} onClick={this.addWorkplan.bind(this)}/>);
      
          let listViewPageProps = {};
          listViewPageProps.showCheck = showCheck;
          listViewPageProps.store = list;
          listViewPageProps.onRowClick = this.onRowClick.bind(this);
          listViewPageProps.getRowProps = this.getRowProps;
          listViewPageProps.customHeight = customHeight;
          listViewPageProps.renderSeparator = separator;
          // if(store.params.rightType){
          //   listViewPageProps.heightSpace = 50;
          // }
          let crmIDs = "";
          if(params.customerId){
            crmIDs = params.customerId;
          }
          return (
            <div className="crm-list-content">
              <div className="crm_contact_list">
              <ListViewPage.Normal
                  {...listViewPageProps}
              />
              </div>
              <RouteLayout.Frame
                id="wpCreateLayout"
                path={wpCreateLayout.path}
                iframeProps={{
                  src: "/spa/workplan/static4mobile/index.html#/create?fromType=crm&workPlanTypeOptions=3&crmIDs="+crmIDs,
                }}
              />

              <RouteLayout.Frame
                id="wpViewLayout"
                path={wpViewLayout.path}
                iframeProps={{
                  src: "/spa/workplan/static4mobile/index.html#/detail?fromType=crm&workplanId="+curWorkplanId,
                }}
              />
            </div>
          );
        }else{
          return (
            <div>
                <Result
                  img={<Icon type="cross-circle-o" className="crm_commerce_initFailedMsg" style={{ fill: '#F13642' }} />}
                  title=""
                  message={initFailedMsg}
                />
            </div>);
        }
    }else{
      return <div className="crm-bg-loading"><ActivityIndicator text="Loading..."/></div>;
    }
  }

  onRowClick(rowData){
    this.setState({curWorkplanId:rowData.id});
    const store = this.state.store;
    const {wpViewLayout} = store;
    this.props.history.push(wpViewLayout.path);
  }

  addWorkplan(){
    const store = this.state.store;
    const {wpCreateLayout} = store;
    this.props.history.push(wpCreateLayout.path);
  }

  getRowProps = (rowData) => {
    const {id,userid,createrid,resourceid,status} = rowData;
    if (status == "1") {
        return {
            withSwipeAction: false,
        }
    } else {
        const store = this.state.store;
        let cancelBtn = {
          text: getLabel("91","删除"),
          onPress: () => {                
            alert('',getLabel('83600','您确认要删除吗？'),[
              { text: getLabel('201','取消'), onPress: () => {} },
              { text: getLabel('83446','确定'), onPress: () => {store.deleteWorkPlan(id);}},
            ]);
          },
          style: { backgroundColor: '#d24545', color: 'white' },
        };
        let completeBtn = {
          text: getLabel("555","完成"),
          onPress: () => {
            store.completeWorkPlan(id);
          },
          style: { backgroundColor: '#da8e2c', color: 'white' },
        };
        const canEdit = userid == createrid;
        const canComplete = (","+resourceid+",").indexOf(","+userid+",") != -1;
        let btns = [];
        if(status == "0"){
          if(canEdit){
            btns.push(completeBtn);
            btns.push(cancelBtn);
          }else{
            if(canComplete){
              btns.push(completeBtn);
            }
          }
        }
        return {
            withSwipeAction: true,
            swipeActionProps:{
              autoClose: true,
              right: btns
            }
        }
    }
  }

  resetListHeight(){
    this.setState({customHeight:"100%"});
    setTimeout(()=>{
      this.setState({customHeight:undefined});
    },10);   
  } 
}